package com.minispider.entity;

import com.minispider.util.HtmlDocument;
import com.minispider.util.Logger;

public class TianyaEntity extends ParamEntity {
	
	public void getNextPageHref(HtmlDocument hd) throws Exception {
		this.referer = this.url;
		this.url = null;
		
		Object[] nodes = hd.getHtmlDocNodesByXPathExp(this.xPathExps.get(0).get(0));

		int size = nodes.length - 1;
    	//System.out.println("#############" + nodes.length);

		String xPathExp = this.xPathExps.get(0).get(1) + size + this.xPathExps.get(0).get(2);
		
    	nodes = hd.getHtmlDocNodesByXPathExp(xPathExp);
    	
    	//System.out.println("#############" + nodes.length);

    	if (nodes.length == 0 || !nodes[0].toString().trim().equals("下一页")) return;
    	
    	xPathExp = this.xPathExps.get(0).get(3) + size + this.xPathExps.get(0).get(4);
		
    	nodes = hd.getHtmlDocNodesByXPathExp(xPathExp);
    	
    	if (nodes.length == 0 || nodes[0].toString().trim().length() == 0) return;

    	this.url = nodes[0].toString().trim();
    	
    	//System.out.println("#############" + this.url);

	}
	
	public void process() throws Throwable {
		
	    if (this.data.size() == 0) return;
	    
	    int size = this.data.get(0).length;
	    

	    for (int i = 0; i < size; i++) {
	    	
	    	Logger.info(this.data.get(5)[i].toString() + "###" + this.data.get(1)[i].toString()
	    			+ "###" + this.data.get(3)[i].toString()+ "###" + this.data.get(4)[i].toString());

    		if (isExpireTime(this.data.get(5)[i].toString(), new java.util.Date(), "MM-dd"))
    		{
    	    	this.isExpire = true;
    	    	break;
    		}
    			    	
    		String aid = (this.data.get(0)[i].toString()).substring((this.data.get(0)[i].toString()).lastIndexOf("/") + 1).split("[.]")[0];
    		int vtime = Integer.valueOf(this.data.get(3)[i].toString());
    		int rtime = Integer.valueOf(this.data.get(4)[i].toString());
    		
    		vtime = vtime > 0 ? vtime : 0;
    		rtime = rtime > 0 ? rtime : 0;
    		
    		//url  title author vtime ctime 
	    	//insert or update
    		int r = this.db.executeUpdate("UPDATE article_info set vtime =" + vtime 
		 							+ ", rtime=" + rtime 
		 							+ " where wid=" + this.ids.get(0) 
		 							+ " and cid=" + this.ids.get(1) 
		 							+ " and aid=" + aid + ";");

    		if (r == 0) {
    			 this.db.executeUpdate(
    					 "insert into article_info(wid,cid,aid,title,author,url,vtime,rtime,cdate)values("
    					 + this.ids.get(0) + "," + this.ids.get(1) + "," + aid + ",'" 
    					 + this.data.get(1)[i].toString() + "','','" 
    					 + this.data.get(0)[i].toString() + "',"
    					 + vtime + ","
    					 + rtime + ","
    					 + "now());");
    		}
    		
	    }
	    
	}
	
	
}
